<?php

namespace App\Http\Controllers\Api\Backstage;

use App\Models\News;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class NewsController extends Controller
{
    public function index()
    {
        $data['newsList'] = News::paginate(20);
        return $this->apiResponse($data);
    }

    public function store(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'newsId' => 'integer|required',
            'caption' => 'required',
            'picture' => 'required',
            'content' => 'required',
            'tag' => 'required'
        ]);
        if ($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $newsId = @$data['newsId'];
        unset($data['newsId']);
        if ($newsId){
            $status = News::where('newsId', $newsId)->update($data);
            if (!$status) {
                return $this->apiResponse('', config('errorCode.EDI_REQ_FAILED'));
            }
        }else{
            $data['createTime'] = date("Y-m-d H:i:s");

            $status = News::create($data);
            if (!$status) {
                return $this->apiResponse('', config('errorCode.INSERT_REQ_FAILED'));
            }
        }
        return $this->apiResponse(true);
    }

    public function show($NewsId)
    {
        $data = News::find($NewsId);
        return $this->apiResponse($data);
    }

    public function destroy($NewsId)
    {
        $data = News::destroy($NewsId);
        return $this->apiResponse($data);
    }
}
